package com.xian.im.modules.avchat.manager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.serializer.RedisSerializer;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @program: xim
 * @description:
 * @author: liru.xian
 * @create: 2021-02-19 16:23
 **/
public abstract class AbsManager {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取符合条件的key
     * @param pattern	表达式
     * @return
     */
    public Set<String> keys(String pattern) {
        Set<String> keys = new LinkedHashSet<>();
        redisTemplate.execute((RedisConnection connection) -> {
            try (Cursor<byte[]> cursor = connection.scan(
                    ScanOptions.scanOptions()
                            .count(Long.MAX_VALUE)
                            .match(pattern)
                            .build()
            )) {
                cursor.forEachRemaining(item -> {
                    keys.add(RedisSerializer.string().deserialize(item));
                });
                return null;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        return keys;
    }
}
